package com.yyh.synctool.client.util;

import java.lang.reflect.Method;

/**
 * 用于打开网址的工具类
 * @author xuan
 * @create 2021/12/2
 */
public class BrowserLauncher
{
    public static void openURL(String url) {
        try {
            browse(url);
        } catch (Exception e) {
            throw new RuntimeException("Failure to open URL");
        }
    }

    private static void browse(String url) throws Exception {
        // 获取操作系统的名字
        String osName = System.getProperty("os.name", "");
        if (osName.startsWith("Mac OS")) {
            // 苹果的打开方式
            Class<?> fileMgr = Class.forName("com.apple.eio.FileManager");
            Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[]{String.class});
            openURL.invoke(null, new Object[] { url });
        } else if (osName.startsWith("Windows")) {
            // Windows的打开方式
            Runtime.getRuntime().exec("rundll32 url.dll, FileProtocolHandler " + url);
        } else {
            // Linux or Unix的打开方式
            String[] browsers = {"firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape"};
            String browser = null;
            for (int count = 0; count < browsers.length && browser == null; count++) {
                //执行代码，在browser有值后跳出，这里是如果进程创建成功了，==0是表示正常结束。
                if (Runtime.getRuntime().exec(new String[] { "which", browsers[count] }).waitFor() == 0) {
                    browser = browsers[count];
                }
            }
            if (browser == null) {
                throw new Exception("Could not find browser.");
            } else {
                Runtime.getRuntime().exec(new String[] { browser, url });
            }
        }
    }
}
